package com.hnit.controllers;

import com.hnit.service.CartService;
import com.hnit.web.DTO.CartDTO;
import com.hnit.web.Utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车API控制器
 */
@RestController
@RequestMapping("/carts")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 将商品添加到指定用户的购物车.
     * POST /carts/{userId}/items
     *
     * @param userId    用户ID
     * @param productId 商品ID
     * @param quantity  数量
     * @return 添加或更新后的购物车项的DTO表示
     */
    @PostMapping("/{userId}/items")
    public ResponseEntity<ResponseResult> addItemToCart(
            @PathVariable Long userId,
            @RequestParam Long productId,
            @RequestParam Integer quantity) {
        try {
            CartDTO cartDTO = cartService.addItemToCart(userId, productId, quantity);
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ResponseResult.ok("商品成功添加到购物车或更新数量").setData(cartDTO));
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("添加商品到购物车失败: " + e.getMessage()));
        }
    }

    /**
     * 获取指定用户购物车中的所有商品列表.
     * GET /carts/{userId}/items
     *
     * @param userId 用户ID
     * @return 包含购物车商品详细信息的 DTO 列表
     */
    @GetMapping("/{userId}/items")
    public ResponseEntity<ResponseResult> listCartItems(@PathVariable Long userId) {
        List<CartDTO> cartDTOs = cartService.listCartItems(userId);
        return ResponseEntity.ok(ResponseResult.ok("查询购物车成功").setData(cartDTOs));
    }

    /**
     * 更新购物车中某条记录的商品数量.
     * PUT /carts/items/{cartId}
     *
     * @param cartId   购物车的唯一ID
     * @param quantity 更新后的新数量
     * @return 操作结果的统一响应
     */
    @PutMapping("/items/{cartId}")
    public ResponseEntity<ResponseResult> updateItemQuantity(
            @PathVariable Long cartId,
            @RequestParam Integer quantity) {
        try {
            boolean success = cartService.updateItemQuantity(cartId, quantity);
            if (success) {
                return ResponseEntity.ok(ResponseResult.ok("购物车商品数量更新成功"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ResponseResult.error("更新购物车商品数量失败，购物车项不存在或数量无效: " + cartId));
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ResponseResult.error("更新购物车商品数量失败: " + e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("更新购物车商品数量失败: " + e.getMessage()));
        }
    }

    /**
     * 从购物车中移除单个商品.
     * DELETE /carts/items/{cartId}
     *
     * @param cartId 要移除的购物车记录的唯一ID
     * @return 操作结果的统一响应
     */
    @DeleteMapping("/items/{cartId}")
    public ResponseEntity<ResponseResult> removeItemFromCart(@PathVariable Long cartId) {
        boolean success = cartService.removeItemFromCart(cartId);
        if (success) {
            return ResponseEntity.ok(ResponseResult.ok("商品已从购物车移除"));
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ResponseResult.error("从购物车移除商品失败，购物车项不存在: " + cartId));
        }
    }

    /**
     * 批量从购物车中移除多个商品.
     * DELETE /carts/items/batch
     *
     * @param cartIds 要移除的购物车记录ID的列表
     * @return 操作结果的统一响应
     */
    @DeleteMapping("/items/batch")
    public ResponseEntity<ResponseResult> removeItemsFromCart(@RequestBody List<Long> cartIds) {
        if (cartIds == null || cartIds.isEmpty()) {
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error("请求参数错误: 购物车ID列表不能为空"));
        }
        boolean success = cartService.removeItemsFromCart(cartIds);
        if (success) {
            return ResponseEntity.ok(ResponseResult.ok("批量商品已从购物车移除"));
        } else {
            // 即使部分失败，只要有删除成功也返回200，但msg可以更详细
            return ResponseEntity.status(HttpStatus.MULTI_STATUS) // 207 Multi-Status 可以用于部分成功
                    .body(ResponseResult.error("部分商品未能成功从购物车移除，请检查日志"));
        }
    }

    /**
     * 清空指定用户的所有购物车项.
     * DELETE /carts/{userId}/clear
     *
     * @param userId 用户ID
     * @return 操作结果的统一响应
     */
    @DeleteMapping("/{userId}/clear")
    public ResponseEntity<ResponseResult> clearCart(@PathVariable Long userId) {
        boolean success = cartService.clearCart(userId);
        // 无论是否清空成功（可能购物车本身就为空），都视为操作完成
        return ResponseEntity.ok(ResponseResult.ok("购物车已清空"));
    }

    /**
     * 获取用户购物车中的商品项总数（不是商品总数量）.
     * GET /carts/{userId}/count
     *
     * @param userId 用户ID
     * @return 购物车中的项目种类数量的统一响应
     */
    @GetMapping("/{userId}/count")
    public ResponseEntity<ResponseResult> getCartItemCount(@PathVariable Long userId) {
        Integer count = cartService.getCartItemCount(userId);
        return ResponseEntity.ok(ResponseResult.ok("查询购物车商品种类数量成功").setData(count));
    }
}